package model

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/schema"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logc"
	"gorm.io/gorm"
)

type UserTotalModel struct {
	ctx context.Context
	db  *gorm.DB
}

func NewUserTotalModel(ctx context.Context, db *gorm.DB) *UserTotalModel {
	return &UserTotalModel{
		ctx: ctx,
		db:  db,
	}
}

func (model *UserTotalModel) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}

	return svc.Db
}

func (model *UserTotalModel) InsertSchema(data *schema.UserTotal) error {
	dbRes := model.getDb().Model(&schema.UserTotal{}).Create(data)
	if err := dbRes.Error; err != nil {
		logc.Error(model.ctx, "UserTotalModel-InsertSchema,err:", err)
		return err
	}

	return nil
}

func (model *UserTotalModel) GetUserByPhone(phone string, areaCode string) (userId int64, err error) {
	if areaCode == "" {
		dbRes := model.getDb().Model(&schema.UserTotal{}).Debug().Select("id").Where("phone =? ", phone).First(&userId)
		if err := dbRes.Error; err != nil && err != gorm.ErrRecordNotFound {
			logc.Error(model.ctx, "UserTotalModel-GetUserByPhone,err:", err)
			return userId, err
		}
	} else {
		dbRes := model.getDb().Model(&schema.UserTotal{}).Debug().Select("id").Where("phone =? and  phone_code=? ", phone, areaCode).First(&userId)
		if err := dbRes.Error; err != nil && err != gorm.ErrRecordNotFound {
			return userId, err
		}
	}

	return userId, nil
}

func (model *UserTotalModel) GetUserByEmail(email string) (userId int64, err error) {
	dbRes := model.getDb().Model(&schema.UserTotal{}).Select("id").Where("email =?", email).First(&userId)
	if err := dbRes.Error; err != nil && err != gorm.ErrRecordNotFound {
		logc.Error(model.ctx, "UserTotalModel-GetUserByEmail,err:", err)
		return userId, err
	}

	return userId, nil
}

func (model *UserTotalModel) GetUserByInviteCode(inviteCode string) (userId int64, err error) {
	dbRes := model.getDb().Model(&schema.UserTotal{}).Select("id").Where("invite_code =?", inviteCode).First(&userId)
	if err := dbRes.Error; err != nil && err != gorm.ErrRecordNotFound {
		logc.Error(model.ctx, "UserTotalModel-GetUserByEmail,err:", err)
		return userId, err
	}

	return userId, nil
}
